<template>
  <div>
    <el-row>
      <el-col :span="11">
        <el-form-item label="品牌">
          <el-select
            placeholder="请选择品牌"
            v-model="searchObj.brandId"
            style="width: 100%"
          >
            <el-option
              :label="brand.name"
              v-for="brand in brands"
              :key="brand.id"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="11">
        <el-form-item label="分类">
          <el-cascader
            v-model="searchObj.categoryId"
            :props="props"
            style="width:100%"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row style="display:flex">
      <el-button type="primary" @click="handleSearch" size="small">
        搜索
      </el-button>
      <el-button size="small" @click="reset">重置</el-button>
    </el-row>

    <div class="tools-div">
      <el-button type="success" size="small" @click="dialogVisible = true">
        添 加
      </el-button>
    </div>

    <el-table :data="list" style="width: 100%">
      <el-table-column prop="categoryName" label="分类" />
      <el-table-column prop="brandName" label="品牌" />
      <el-table-column prop="brandLogo" label="品牌图标" #default="scope">
        <img :src="scope.row.brandLogo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="200" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowUpdateDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDel(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 3, 4, 5]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="initData"
      @current-change="initData"
    />
    <!-- 新增/修改 对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
        <el-form label-width="120px">
          <el-form-item label="品牌">
            <el-select
              class="m-2"
              v-model="categoryBrand.brandId"
              placeholder="选择品牌"
              size="small"
            >
              <el-option
                v-for="item in brands"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader :props="props" v-model="categoryBrand.categoryId" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSaveOrUpdate">
              提交
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { GetAllBrands } from '@/api/brand'
import { GetCategoriesByPid } from '@/api/category'
import {
  GetCategoryBrands,
  GetCategoryBrandById,
  DeleteCategoryBrandById,
  SaveCategoryBrand,
  UpdateCategoryBrand,
} from '@/api/categoryBrand'
//5、修改：
//弹出对话框回显修改的数据
const handleShowUpdateDialog = async row => {
  const { data } = await GetCategoryBrandById(row.id)
  categoryBrand.value = data
  dialogVisible.value = true
}
//提交更新请求
const handleUpdate = async () => {
  // if(categoryBrand.value.categoryId && categoryBrand.value.categoryId.length)
  console.log(typeof categoryBrand.value.categoryId)
  if (
    typeof categoryBrand.value.categoryId === 'object' &&
    categoryBrand.value.categoryId.length === 3
  ) {
    categoryBrand.value.categoryId = categoryBrand.value.categoryId[2]
  }
  await UpdateCategoryBrand(categoryBrand.value)
  dialogVisible.value = false
  initData()
}
//4、新增分类品牌对话框
const dialogVisible = ref(false)
const categoryBrand = ref({})
const handleSaveOrUpdate = () => {
  if (categoryBrand.value.id) {
    handleUpdate()
  } else {
    handleSave()
  }
}
const handleSave = async () => {
  categoryBrand.value.categoryId = categoryBrand.value.categoryId[2]
  //提交新增请求
  if (categoryBrand.value.brandId && categoryBrand.value.categoryId) {
    await SaveCategoryBrand(categoryBrand.value)
  }
  dialogVisible.value = false
  initData()
}

//3、删除分类品牌：
const handleDel = async row => {
  await DeleteCategoryBrandById(row.id)
  ElMessage.success('删除成功')
  initData()
}
//2、条件查询：搜索按钮事件函数
const handleSearch = () => {
  console.log(searchObj.value)
  //只获取选中的三级分类id的第三级的id
  if (searchObj.value.categoryId && searchObj.value.categoryId.length === 3) {
    searchObj.value.categoryId = searchObj.value.categoryId[2]
  } else {
    searchObj.value.categoryId = null
  }
  //异步加载分页数据展示
  initData()
}
//重置
const reset = () => {
  searchObj.value = {}
  pageNum.value = 1
  pageSize.value = 3
  initData()
}
//1、页面初始化
onMounted(() => {
  getAllBrands()
  initData()
})
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
const list = ref([])
//查询数据
const initData = async () => {
  const { data } = await GetCategoryBrands(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )
  list.value = data.list
  total.value = data.total
  //   console.log(data)
}

const searchObj = ref({})
//1.1 查询所有品牌
const brands = ref([])
const getAllBrands = async () => {
  const { data } = await GetAllBrands()
  brands.value = data
}
//1.2 分类级联选择器：数据初始化
//级联选择器配置
const props = {
  lazy: true, //开启懒加载：点击一级才会加载他的下一级数据
  label: 'name', //表示使用分类数据的name值当做标题
  leaf: 'leaf', //表示使用的分类数据的哪个属性用来判断自己是否为叶子节点(不是叶子节点会显示箭头)
  value: 'id', //表示选中分类数据时，收集哪个属性值
  async lazyLoad(node, resolve) {
    // 开启懒加载后，懒加载数据的方法
    console.log('....', node)
    //1、第一次lazyLoad调用时，加载pid=0的分类数据展示
    //3、第N次点击时，使用上一级的id当做父id查询
    let pid = 0
    if (node.data && node.data.id) {
      pid = node.data.id
    }
    const { data } = await GetCategoriesByPid(pid)
    data.forEach(cate => {
      cate.leaf = !cate.hasChildren //如果遍历的分类有下一级，设置它不是叶子节点
    })
    //2、将加载到的数据渲染到级联选择器中展示
    resolve(data)
  },
}
</script>
